package lib.gui;

import java.awt.Point;
import java.io.File;
import java.util.concurrent.ConcurrentHashMap;

import javax.swing.JFrame;
import javax.swing.JTabbedPane;

import lib.Base.Conversation;
import lib.Base.Message;
import lib.Common.Path;

import org.swixml.SwingEngine;

public class GuiChat {
	/**
	 * Class to store and handle all chat conversations
	 */
	private static ConcurrentHashMap<String, GuiChatWindow> chatWindows;
	private static SwingEngine engine;
	private static JTabbedPane chatTabs;
	private static JFrame chatContainer;
	

	public GuiChat(Point windowPosition, int windowWidth) {
		try {
			// Render xml document
			engine = new SwingEngine(this);
			engine.render(new File(Path.GUI_PATH + "gui-chat-container.xml"));

			int x = (int) ((windowPosition.getX() + windowWidth));
			int y = (int) (windowPosition.getY());
			
			// Set the location of the chat container
			chatContainer.setLocation(x, y);

		} catch (Exception e) {
			e.printStackTrace();
		}
		chatWindows = new ConcurrentHashMap<String, GuiChatWindow>();

	}
	
	/**
	 *  This method is called by the objectHandler and prints the message obj
	 */
	public static void sendToChatWindow(Message msg, String id) {
		// Get the chat window
		GuiChatWindow tmpReference = chatWindows.get(id);
		
		if(tmpReference != null){
			// Chatwindow exist, update textarea
			tmpReference.update(msg);
		}else{
			// No chatwindow exist, create one and update the textarea
			tmpReference = new GuiChatWindow(engine, new Conversation(id, "NewWindow"));
			chatWindows.put(id, tmpReference);
			tmpReference.create();
			tmpReference.update(msg);
			
			// Check visibility of the root container
			if (!chatContainer.isVisible()) {
				chatContainer.setVisible(true);
			}
		}
	}
	
	public void addChatWindow(String userId, String userName) throws Exception {
		
		// Check visibility of the root container
		if (!chatContainer.isVisible()) {
			chatContainer.setVisible(true);
		}
		
		// Check for older conversation's with the given userId
		if (!chatWindows.containsKey(userId)) {
			// No conversation, create one
			GuiChatWindow tmpReference = new GuiChatWindow(engine, new Conversation(userId, "NewWindow"));
			chatWindows.put(userId, tmpReference);
			tmpReference.create();

		} else {
			// Conversation exist, get it and make it visible
			GuiChatWindow tmp = chatWindows.get(userId);
			tmp.create();
			chatTabs.setSelectedComponent(tmp.getPanel());
		}
	}
	
	public static GuiChatWindow getChatWindowByUserId(String userId) {
		return chatWindows.get(userId);
	}
	
	public static void setFrameVisibility(boolean visible) {
		chatContainer.setVisible(visible);
	}
	
	public static JTabbedPane getTabbedPane() {
		return chatTabs;
	}
}